package service

import (
	"server/global"
	"server/model"

	"gorm.io/gorm"
)

//  get by id
func DeviceGet(d model.Device) (*model.Device, error) {
	var device model.Device
	err := global.DB.Where("id = ?", d.ID).First(&device).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return &device, nil
}

func DeviceExist(d model.Device) (bool, error) {
	var device model.Device
	err := global.DB.Where("id = ?", d.ID).First(&device).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	if device.ID > 0 {
		return true, err
	}
	return false, nil
}

func DeviceExistBySn(d model.Device) (bool, error) {
	var device model.Device
	err := global.DB.Where("sn = ?", d.Sn).First(&device).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	if device.ID > 0 {
		return true, err
	}
	return false, nil
}

// get by sn
func DeviceGetBySn(d model.Device) (*model.Device, error) {
	var device model.Device
	err := global.DB.Where("sn = ?", d.Sn).First(&device).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return &device, nil
}

// get all
func DeviceGetAll() ([]*model.Device, error) {
	var devices []*model.Device
	err := global.DB.Raw("SELECT * FROM devices").Scan(&devices).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return devices, nil
}

// get all
func DeviceGetLock() ([]*model.Device, error) {
	var devices []*model.Device
	err := global.DB.Find(&devices).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return devices, nil
}

// add
func DeviceAdd(d model.Device) error {
	if err := global.DB.Create(&d).Error; err != nil {
		return err
	}
	return nil
}

// edit
func DeviceEdit(d model.Device) error {
	if err := global.DB.Model(&model.Device{}).Where("sn = ?", d.Sn).Save(d).Error; err != nil {
		return err
	}
	return nil
}

// edit by id
func DeviceEditByID(d model.Device) error {
	if err := global.DB.Model(&model.Device{}).Where("id = ?", d.ID).Save(d).Error; err != nil {
		return err
	}
	return nil
}

// edit online
func DeviceEditOnline(d model.Device) error {
	if err := global.DB.Model(&model.Device{}).Where("sn = ?", d.Sn).Save(d).Error; err != nil {
		return err
	}
	return nil
}

// delete
func DeviceDelete(d model.Device) error {
	if err := global.DB.Delete(&d).Error; err != nil {
		return err
	}
	return nil
}
